package com.ytlz.dmcs.model.system.view;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private MongoTemplate mongoTemplate;

	public MongoTemplate getMongoTemplate() {
		return mongoTemplate;
	}

	public void setMongoTemplate(MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}
	
	@GetMapping("getusers")
    public String getUsers() {       
        return "Hello Spring Security";
    }
	
	@PostMapping("login")
    public Map<String,Object> login(String username,String password) {
		Map<String,Object> reulst = new HashMap<String, Object>();
        return reulst;
    }
	
	@RequestMapping("getData")
	@ResponseBody
 	public Map<String, Object> getData(HttpServletRequest request,@RequestParam(value="type" ,required=true) String type) {
		
		Map<String,Object> result = new HashMap<String, Object>();  
		Query query = new Query();
		Enumeration<String> names = request.getParameterNames();
		Criteria c = null;
		
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			Pattern pattern = Pattern.compile("^.*"+ request.getParameter(name) +".*$", Pattern.CASE_INSENSITIVE);
			if(name.startsWith("query.")) {
				String key = name.replace("query.", "");
				if(c==null) {
					c=Criteria.where(key).regex(pattern);
				}else {
					c.and(key).regex(pattern);
				}
			}
		}
		if(c!=null) {			
			query.addCriteria(c);
		}
		
		if(request.getParameter("sort")!=null && request.getParameter("order")!=null) {
			String sort=request.getParameter("sort");
			String order=request.getParameter("order");
			Direction direction= order.toLowerCase().equals("asc")?Direction.ASC:Direction.DESC;
			Order orderData = new Order(direction, sort);
			query.with(Sort.by(orderData));
		}
		
		if(request.getParameter("page")!=null && request.getParameter("rows")!=null) {			
			String page = request.getParameter("page");
			String rows = request.getParameter("rows");
			int pageNumber  = Integer.parseInt(page)-1;
			int limit = Integer.parseInt(rows);
			query.with(PageRequest.of(pageNumber, limit));
		}

		
		long count = this.getMongoTemplate().count(query, type);		
		List<Document> rows = this.getMongoTemplate().find(query, Document.class, type);
		List<Document> rowsList = new ArrayList<Document>();
		for (Document document : rows) {
			ObjectId id = document.getObjectId("_id");
			document.append("id", id.toString());
			if(document.get("parent_id")!=null && document.get("parent_id").toString().trim().length()>0) {
				Document parentObj = this.getMongoTemplate().findById(new ObjectId(document.get("parent_id").toString()), Document.class, type);
				if(parentObj!=null) {
					document.append("parent_name", parentObj.getString("text"));
				}
			}
			
			rowsList.add(document);
		}
		result.put("total", count);
		result.put("rows", rowsList);			
		return result;
	}
}
